﻿using Jive.Helpers;
using Jive.Models;
using NetworkCommsDotNet;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using System.Windows.Media;
using GalaSoft.MvvmLight.Command;
using System.Threading;
using Jive.CustomControls;
using Jive.Network;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using Jive.Settings;
using JmShared;
using Jive.User;

namespace Jive.ViewModels
{
    public class ViewModelMainPage : ViewModelBase
    {
        private object LockObject = new object();
        private DateTime LastMessageReceivedTime { get; set; }
        public ObservableCollection<MessageModel> Messages { get; set; }
        public ObservableCollection<ContactModel> Contacts { get; set; }
        public ObservableCollection<EmoticonModel> CustomEmoticons { get; set; }
        public ObservableCollection<EmoticonModel> DefaultEmoticons { get; set; }
        public ObservableCollection<EmoticonModel> RecentlyUsedEmoticons { get; set; }
        public RelayCommand<ContactModel> OpenPmCommand { get; private set; }
        public RelayCommand<ContactModel> ClosePmCommand { get; private set; }
        public RelayCommand<ContactModel> AddCustomEmoticonsCommand { get; private set; }
        public RelayCommand EmoticonPopupBackspaceCommand { get; private set; }
        public RelayCommand<EmoticonClickedEventArgs> EmoticonPopupClickEmoticonCommand { get; private set; }
        public RelayCommand<SendMessageEventArgs> SendMessageCommand { get; private set; }
        public RelayCommand<System.Windows.Input.GestureEventArgs> ChatControlWindowTappedCommand { get; private set; }
        public RelayCommand<string> EmoticonPopupSendMessageCommand { get; private set; }
        public RelayCommand AppBarSettingsCommand { get; private set; }
        public RelayCommand AppBarConnectCommand { get; private set; }
        public RelayCommand AppBarEmoticonsCommand { get; private set; }
        public RelayCommand PopupConnectCommand { get; private set; }
        public RelayCommand<MessageQueueUpdateEventArgs> MessageQueueItemReceivedCommand { get; private set; }

        //private ObservableCollection<EmoticonModel> _defaultEmoticon;
        //public ObservableCollection<EmoticonModel> DefaultEmoticons
        //{
        //    get { return _defaultEmoticon; }
        //    set
        //    {
        //        if (_defaultEmoticon != value)
        //        {
        //            _defaultEmoticon = value;
        //          //  RaisePropertyChanged("DefaultEmoticons");
        //        }
        //    }
        //}

        //private ObservableCollection<EmoticonModel> _customEmoticons;
        //public ObservableCollection<EmoticonModel> CustomEmoticons
        //{
        //    get { return _customEmoticons; }
        //    set
        //    {
        //        if (_customEmoticons != value)
        //        {
        //            _customEmoticons = value;
        //           // RaisePropertyChanged("CustomEmoticons");
        //        }
        //    }
        //}

        //private ObservableCollection<EmoticonModel> _recentlyUsedEmoticons;
        //public ObservableCollection<EmoticonModel> RecentlyUsedEmoticons
        //{
        //    get { return _recentlyUsedEmoticons; }
        //    set
        //    {
        //        if (_recentlyUsedEmoticons != value)
        //        {
        //            _recentlyUsedEmoticons = value;
        //          //  RaisePropertyChanged("RecentlyUsedEmoticons");
        //        }
        //    }
        //}

        private int _emoticonControlPivotIndex;
        public int EmoticonControlPivotIndex
        {
            get { return _emoticonControlPivotIndex; }
            set
            {
                if (_emoticonControlPivotIndex != value)
                {
                    _emoticonControlPivotIndex = value;
                    RaisePropertyChanged("EmoticonControlPivotIndex");
                }
            }
        }


        private int _inputTextSelectionLength;
        public int InputTextSelectionLength
        {
            get { return _inputTextSelectionLength; }
            set
            {
                if (_inputTextSelectionLength != value)
                {
                    _inputTextSelectionLength = value;
                    RaisePropertyChanged("InputTextSelectionLength");
                }
            }
        }


        private int _intputTextSelectionStart;
        public int InputTextSelectionStart
        {
            get { return _intputTextSelectionStart; }
            set
            {
                if (_intputTextSelectionStart != value)
                {
                    _intputTextSelectionStart = value;
                    RaisePropertyChanged("InputTextSelectionStart");
                }
            }
        }

        private string _inputText;
        public string InputText
        {
            get { return _inputText; }
            set
            {
                if (_inputText != value)
                {
                    _inputText = value;
                    RaisePropertyChanged("InputText");
                }
            }
        }

        private bool _showKeyboard;

        public bool ShowKeyboard
        {
            get { return _showKeyboard; }
            set
            {
                if (_showKeyboard != value)
                {
                    _showKeyboard = value;
                    RaisePropertyChanged("ShowKeyboard");
                }
            }
        }

        private bool _showFauxKeyboardGrid;

        public bool ShowFauxKeyboardGrid
        {
            get { return _showFauxKeyboardGrid; }
            set
            {
                if (_showFauxKeyboardGrid != value)
                {
                    _showFauxKeyboardGrid = value;
                    RaisePropertyChanged("ShowFauxKeyboardGrid");
                }
            }
        }

        private int _selectedPivotItemIndex;

        public int SelectedPivotItemIndex
        {
            get { return _selectedPivotItemIndex; }
            set
            {
                if (_selectedPivotItemIndex != value)
                {
                    _selectedPivotItemIndex = value;
                    RaisePropertyChanged("SelectedPivotItemIndex");
                }
            }
        }

        private bool _isConnectButtonEnabled;

        public bool IsConnectButtonEnabled
        {
            get { return _isConnectButtonEnabled; }
            set
            {
                if (_isConnectButtonEnabled != value)
                {
                    _isConnectButtonEnabled = value;
                    RaisePropertyChanged("IsConnectButtonEnabled");
                }
            }
        }

        private Color _appBarForegroundColor;

        public Color AppBarForegroundColor
        {
            get { return _appBarForegroundColor; }
            set
            {
                if (_appBarForegroundColor != value)
                {
                    _appBarForegroundColor = value;
                    RaisePropertyChanged("AppBarForegroundColor");
                }
            }
        }

        private bool _showConnectPopup;

        public bool ShowConnectPopup
        {
            get { return _showConnectPopup; }
            set
            {
                if (_showConnectPopup != value)
                {
                    _showConnectPopup = value;
                    RaisePropertyChanged("ShowConnectPopup");
                }
            }
        }

        private bool _showEmoticonPopup;

        public bool ShowEmoticonPopup
        {
            get { return _showEmoticonPopup; }
            set
            {


                if (_showEmoticonPopup != value)
                {
                    _showEmoticonPopup = value;
                    RaisePropertyChanged("ShowEmoticonPopup");
                }
            }
        }

        private Uri _connectButtonIconUri;

        public Uri ConnectButtonIconUri
        {
            get { return _connectButtonIconUri; }
            set
            {
                if (_connectButtonIconUri != value)
                {
                    _connectButtonIconUri = value;
                    RaisePropertyChanged("ConnectButtonIconUri");
                }
            }
        }

        private string _connectButtonDisplayText;
        public string ConnectButtonDisplayText
        {
            get { return _connectButtonDisplayText; }
            set
            {
                if (value != this._connectButtonDisplayText)
                {
                    this._connectButtonDisplayText = value;
                    RaisePropertyChanged("ConnectButtonDisplayText");
                }
            }
        }

        private Uri _emoticonButtonIconUri;

        public Uri EmoticonButtonIconUri
        {
            get { return _emoticonButtonIconUri; }
            set
            {
                if (value != this._emoticonButtonIconUri)
                {
                    this._emoticonButtonIconUri = value;
                    RaisePropertyChanged("EmoticonButtonIconUri");
                }
            }
        }

        private string _emoticonButtonDisplayText;

        public string EmoticonButtonDisplayText
        {
            get { return _emoticonButtonDisplayText; }
            set
            {
                if (_emoticonButtonDisplayText != value)
                {
                    _emoticonButtonDisplayText = value;
                    RaisePropertyChanged("EmoticonButtonDisplayText");
                }
            }
        }


        private int _remainingMessages;

        public int RemainingMessages
        {
            get { return _remainingMessages; }
            set
            {
                if (value != this._remainingMessages)
                {
                    this._remainingMessages = value;
                    RaisePropertyChanged("RemainingMessages");
                }
            }
        }
        public bool ShowChatControl
        {
            get
            {
                return RemainingMessages == 0;
            }
        }
        public bool ShowLoadAnimation
        {
            get
            {
                return RemainingMessages > 0;
            }
        }
        public ViewModelMainPage()
        {

            RemainingMessages = 0;
            Contacts = new ObservableCollection<ContactModel>();
            Messages = new ObservableCollection<MessageModel>();
            DefaultEmoticons = new ObservableCollection<EmoticonModel>();
            CustomEmoticons = new ObservableCollection<EmoticonModel>();
            RecentlyUsedEmoticons = new ObservableCollection<EmoticonModel>();
            if (DesignerProperties.IsInDesignTool)
                return;

            InputText = string.Empty;
            AppBarForegroundColor = StaticSettings.MaroonColor;
            DefaultEmoticons = CreateDefaultEmoticonList();
            CreateCustomEmoticons();
            UpdateRecentlyUsedEmoticonList();
            IsConnectButtonEnabled = true;
            ConnectButtonIconUri = new Uri("/Assets/AppBar/appbar.door.enter.png", UriKind.Relative);
            EmoticonButtonIconUri = new Uri("/Assets/AppBar/appbar.smiley.happy.png", UriKind.Relative);
            ConnectButtonDisplayText = "Log in";
            EmoticonButtonDisplayText = "Emoticons";
            OpenPmCommand = new RelayCommand<ContactModel>(OpenPmAction);
            ClosePmCommand = new RelayCommand<ContactModel>(ClosePmAction);
            AddCustomEmoticonsCommand = new RelayCommand<ContactModel>(AddCustomEmoticonsAction);
            AppBarConnectCommand = new RelayCommand(AppBarConnectAction);
            AppBarSettingsCommand = new RelayCommand(AppBarSettingsAction);
            AppBarEmoticonsCommand = new RelayCommand(AppBarEmoticonsAction);
            PopupConnectCommand = new RelayCommand(PopupConnectCommandAction);
            EmoticonPopupBackspaceCommand = new RelayCommand(EmoticonPopupBackspaceCommandAction);
            EmoticonPopupClickEmoticonCommand = new RelayCommand<EmoticonClickedEventArgs>(EmoticonPopupClickEmoticonCommandAction);
            EmoticonPopupSendMessageCommand = new RelayCommand<string>(message => EmoticonPopupSendMessageCommandAction(message), message => Client.ClientInstance.IsLoggedIn);
            SendMessageCommand = new RelayCommand<SendMessageEventArgs>(SendMessageCommandAction);
            ChatControlWindowTappedCommand = new RelayCommand<System.Windows.Input.GestureEventArgs>(ChatControlWindowTappedCommandAction);
            MessageQueueItemReceivedCommand = new RelayCommand<MessageQueueUpdateEventArgs>(MessageQueueItemsReceivedCommandAction);
            PropertyChanged += ViewModelMainPage_PropertyChanged;

        }

        void ViewModelMainPage_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            switch (e.PropertyName)
            {
                case "RemainingMessages":
                    RaisePropertyChanged("ShowChatControl");
                    RaisePropertyChanged("ShowLoadAnimation");
                    break;
                case "ShowEmoticonPopup":
                    if (this.ShowEmoticonPopup == true)
                    {
                        ShowKeyboard = false;
                        EmoticonButtonDisplayText = "Keyboard";
                        EmoticonButtonIconUri = new Uri("/Assets/AppBar/appbar.input.keyboard.png", UriKind.Relative);
                    }
                    else
                    {
                        EmoticonButtonDisplayText = "Emoticons";
                        EmoticonButtonIconUri = new Uri("/Assets/AppBar/appbar.smiley.happy.png", UriKind.Relative);
                    }
                    if (!ShowKeyboard)
                        ShowFauxKeyboardGrid = this.ShowEmoticonPopup;
                    break;
                case "ShowConnectPopup":
                    if (this.ShowConnectPopup == true)
                    {
                        ShowKeyboard = false;
                        ShowEmoticonPopup = false;
                    }
                    break;
                case "SelectedPivotItemIndex":
                    ShowFauxKeyboardGrid = false;
                    ShowConnectPopup = false;
                    break;
                case "ShowKeyboard":
                    if (this.ShowKeyboard == true)
                    {
                        ShowEmoticonPopup = false;
                    }
                    if (!ShowEmoticonPopup)
                        ShowFauxKeyboardGrid = this.ShowKeyboard;
                    break;
            }
        }

        private void UpdateRecentlyUsedEmoticonList(EmoticonModel model = null)
        {
            if (model == null)
            {
                if (RecentlyUsedEmoticons == null)
                    RecentlyUsedEmoticons = new ObservableCollection<EmoticonModel>();
                foreach (var v in AppSettings.AppSettingsInstance.RecentlyUsedCustomEmoticons)
                {
                    model = CustomEmoticons.FirstOrDefault(x => (string)x.EmoticonShortcut == v.Key);
                    if (!RecentlyUsedEmoticons.Contains(model))
                        RecentlyUsedEmoticons.Add(model);
                }
                foreach (var v in AppSettings.AppSettingsInstance.RecentlyUsedDefaultEmoticons)
                {
                    model = DefaultEmoticons.FirstOrDefault(x => ((string[])x.EmoticonShortcut).SequenceEqual(v.Key));
                    if (!RecentlyUsedEmoticons.Contains(model))
                        RecentlyUsedEmoticons.Add(model);
                }
            }
            else
            {
                if (!RecentlyUsedEmoticons.Contains(model))
                    RecentlyUsedEmoticons.Add(model);
            }
            if (RecentlyUsedEmoticons == null)
                return;
            var sortedList = RecentlyUsedEmoticons.ToList();
            sortedList.Sort((x, y) =>
             {
                 int thisCount = 0;
                 if (x.EmoticonType == EmoticonType.CustomEmoticon)
                     thisCount = AppSettings.AppSettingsInstance.RecentlyUsedCustomEmoticons[(string)x.EmoticonShortcut];
                 else if (x.EmoticonType == EmoticonType.DefaultEmoticon)
                 {
                     var key = (string[])x.EmoticonShortcut;
                     thisCount = AppSettings.AppSettingsInstance.RecentlyUsedDefaultEmoticons.Where(z => z.Key.SequenceEqual(key)).First().Value;
                 }

                 int otherCount = 0;

                 if (y.EmoticonType == EmoticonType.DefaultEmoticon)
                 {
                     var key = (string[])y.EmoticonShortcut;
                     otherCount = AppSettings.AppSettingsInstance.RecentlyUsedDefaultEmoticons.Where(z => z.Key.SequenceEqual(key)).First().Value;
                 }
                 else if (y.EmoticonType == EmoticonType.CustomEmoticon)
                     otherCount = AppSettings.AppSettingsInstance.RecentlyUsedCustomEmoticons[(string)y.EmoticonShortcut];

                 if (thisCount > otherCount)
                     return 0;
                 else
                     return 1;

             });
            RecentlyUsedEmoticons = new ObservableCollection<EmoticonModel>(sortedList);
        }
        public void IncrementContactUnreadPmCount(string userName)
        {
            ContactModel contact = this.Contacts.First(x => x.UserName == userName);
            if (contact != null)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() => contact.UnreadMessageCount++);
            }
        }

        private void MessageQueueItemsReceivedCommandAction(MessageQueueUpdateEventArgs args)
        {
            if (args.TotalMessagesInQueue > 10)
            {
                Deployment.Current.Dispatcher.BeginInvoke(() => this.RemainingMessages = args.TotalMessagesInQueue - args.ReceivedMessages);
            }
        }
        public void RunOnNetworkConnect()
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                ConnectButtonIconUri = new Uri("/Assets/AppBar/appbar.door.leave.png", UriKind.Relative);
                ConnectButtonDisplayText = "Log out";
                AppBarForegroundColor = Colors.Green;
                IsConnectButtonEnabled = true;
            });
        }


        public void RunOnNetworkDisconnect()
        {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                Contacts.Clear();
                ConnectButtonIconUri = new Uri("/Assets/AppBar/appbar.door.enter.png", UriKind.Relative);
                ConnectButtonDisplayText = "Log in";
                AppBarForegroundColor = StaticSettings.MaroonColor;
                IsConnectButtonEnabled = true;
            });
        }

        public override void Cleanup()
        {
            base.Cleanup();
        }
        public void CreateCustomEmoticons()
        {
            CustomEmoticons = CreateCustomEmoticonList();
        }

        private void ChatControlWindowTappedCommandAction(System.Windows.Input.GestureEventArgs args)
        {
            this.ShowEmoticonPopup = false;

            ShowConnectPopup = false;
            ShowKeyboard = false;
        }


        private ObservableCollection<EmoticonModel> CreateDefaultEmoticonList()
        {
            ObservableCollection<EmoticonModel> list = new ObservableCollection<EmoticonModel>();
            foreach (KeyValuePair<string[], string> kvp in StaticSettings.DefaultEmoticons)
            {
                list.Add(new EmoticonModel() { EmoticonShortcut = kvp.Key, EmoticonType = EmoticonType.DefaultEmoticon, EmoticonPath = "/Assets/DefaultEmoticons/" + kvp.Value });
            }
            return list;
        }


        public ObservableCollection<EmoticonModel> CreateCustomEmoticonList()
        {
            ObservableCollection<EmoticonModel> list = new ObservableCollection<EmoticonModel>();
            foreach (KeyValuePair<string, string> kvp in StaticSettings.CustomEmoticons)
            {
                list.Add(new EmoticonModel() { EmoticonShortcut = kvp.Key, EmoticonType = EmoticonType.CustomEmoticon, EmoticonPath = kvp.Value });
            }
            return list;
        }
        public void RemoveOfflineContact(string userName)
        {
            ContactModel model = Contacts.FirstOrDefault(x => x.UserName == userName);
            if (model != null)
            {
                if (!Client.ClientInstance.ConnectedClients.Values.Any(x => x.UserName == userName))
                {
                    Deployment.Current.Dispatcher.BeginInvoke(() => Contacts.Remove(model));

                }
            }
        }

        public void AddOrUpdateContact(UserInfo user)
        {

            lock (LockObject)
            {
                Client.ClientInstance.ConnectedClients[user.UserID] = user;
                ContactModel contact = Contacts.FirstOrDefault(x => x.UserName == user.UserName);
                if (contact == null)
                {
                    //Deployment.Current.Dispatcher.BeginInvoke(() =>
                    //    {
                    contact = new ContactModel(user.UserID, user.NickName);
                    UpdateContactStatus(contact, user.ClientStatus);
                    Contacts.Add(contact);
                    //});
                }
                else
                {
                    //Deployment.Current.Dispatcher.BeginInvoke(() =>
                    //    {
                    UpdateContactStatus(contact, user.ClientStatus);
                    //});
                }
            }
        }
        private void UpdateContactStatus(ContactModel contact, ClientStatus status)
        {
            switch (status)
            {
                case ClientStatus.Afk:
                    contact.StatusText = "Away";
                    contact.ClientStatusBrush = (LinearGradientBrush)App.Current.Resources["ButtonGradientBrushAfk"];
                    break;
                case ClientStatus.Available:
                    contact.StatusText = "Available";
                    contact.ClientStatusBrush = (LinearGradientBrush)App.Current.Resources["ButtonGradientBrushOnline"];
                    break;
                case ClientStatus.Busy:
                    contact.StatusText = "Busy";
                    contact.ClientStatusBrush = (LinearGradientBrush)App.Current.Resources["ButtonGradientBrushBusy"];
                    break;
            }
        }

        private void SendMessageCommandAction(SendMessageEventArgs args)
        {
            SendMessage(args.Text);
        }

        private void EmoticonPopupBackspaceCommandAction()
        {
            int index = this.InputTextSelectionStart - 1;
            if (index > 0)
            {
                this.InputText = InputText.Remove(index, 1);
                this.InputTextSelectionStart = index;
                this.InputTextSelectionLength = 0;
            }
            else
                this.InputText = string.Empty;
        }

        private void EmoticonPopupClickEmoticonCommandAction(EmoticonClickedEventArgs args)
        {
            EmoticonModel model = args.Model;
            string key = string.Empty;

            if (model.EmoticonType == EmoticonType.CustomEmoticon)
            {
                key = model.EmoticonShortcut.ToString();
                if (!AppSettings.AppSettingsInstance.RecentlyUsedCustomEmoticons.ContainsKey(key))
                    AppSettings.AppSettingsInstance.RecentlyUsedCustomEmoticons.Add(key, 0);
                AppSettings.AppSettingsInstance.RecentlyUsedCustomEmoticons[key]++;
            }
            else if (model.EmoticonType == EmoticonType.DefaultEmoticon)
            {
                string[] keyArray = model.EmoticonShortcut as string[];
                key = keyArray[0];
                if (!AppSettings.AppSettingsInstance.RecentlyUsedDefaultEmoticons.ContainsKey(keyArray))
                    AppSettings.AppSettingsInstance.RecentlyUsedDefaultEmoticons.Add(keyArray, 0);
                AppSettings.AppSettingsInstance.RecentlyUsedDefaultEmoticons[keyArray]++;

            }
            UpdateRecentlyUsedEmoticonList(model);
            InsertEmoticon(key);

        }

        private void InsertEmoticon(string key)
        {
            int offset = InputTextSelectionStart;
            InputTextSelectionLength = 0;
            InputText = InputText.Insert(offset, key);
            InputTextSelectionStart = offset + key.Length;
        }
        private void EmoticonPopupSendMessageCommandAction(string messageText)
        {
            SendMessage(messageText);
            ShowEmoticonPopup = false;
            ShowKeyboard = true;
        }

        private void PopupConnectCommandAction()
        {
            ShowConnectPopup = false;
            IsConnectButtonEnabled = false;
            if (Client.ClientInstance.IsLoggedIn)
            {
                App.Connection.SendStatusMessage(MessageType.Logout, string.Empty);
                TCPConnection.GetConnection(App.Connection.MasterConnectionInfo).ConnectionAlive(5);
            }
            else
            {
                if (Client.ClientInstance.CurrentUserInfo != null && AppSettings.AppSettingsInstance.UsernameSetting != Client.ClientInstance.CurrentUserInfo.UserName)
                    Client.Clear();

                App.Connection.Login(AppSettings.AppSettingsInstance.ServerSetting, AppSettings.AppSettingsInstance.UsernameSetting, AppSettings.AppSettingsInstance.PasswordSetting, StaticSettings.ServerPort);
            }
        }

        private void AppBarSettingsAction()
        {
            this.ShowEmoticonPopup = false;
            this.ShowConnectPopup = false;
            Messenger.Default.Send(new Uri("//Views/SettingsPage.xaml", UriKind.Relative));
        }
        private void AppBarConnectAction()
        {
            ShowConnectPopup = !ShowConnectPopup;
        }
        private void AppBarEmoticonsAction()
        {
            if (ShowEmoticonPopup)
            {
                ShowKeyboard = true;
                ShowEmoticonPopup = false;
                return;
            }

            ShowEmoticonPopup = true;
        }
        public void SendMessage(string text)
        {
            if (Client.ClientInstance.IsLoggedIn)
            {
                MessageType mt = MessageType.Message;
                AddMessage(Client.ClientInstance.CurrentUserInfo, text, mt, DateTime.Now);
                ChatMessage msg = new ChatMessage()
                {
                    Message = text,
                    MessageType = mt,
                    SenderID = Client.ClientInstance.CurrentUserInfo.UserID,
                    MessageRelayTime = DateTime.Now
                };

                if (!App.Connection.SendMessage(msg))
                {
                    AddMessage(Client.RedText, String.Format("Could not deliver message: \r\n{0}", msg.Message), MessageType.Error, DateTime.Now);
                }
            }
            else
            {
                Messenger.Default.Send("Not logged in");
            }
            this.InputText = string.Empty;
        }
        private void ClosePmAction(ContactModel contact)
        {
            if (!Client.ClientInstance.PrivateMessages.ContainsKey(contact.UserName))
                return;

            Client.ClientInstance.PrivateMessages.Remove(contact.UserName);
            contact.PmStatus = string.Empty;
            contact.UnreadMessageCount = 0;
        }
        private void AddCustomEmoticonsAction(ContactModel contact)
        {
            Messenger.Default.Send(new Uri("//Views/GetEmoticonsPage.xaml?userID=" + Uri.EscapeDataString(contact.UserID), UriKind.Relative));
        }
        private void OpenPmAction(ContactModel contact)
        {
            if (contact == null)
                return;

            if (!Client.ClientInstance.PrivateMessages.ContainsKey(contact.UserName))
            {
                Client.ClientInstance.PrivateMessages[contact.UserName] = new List<ChatMessage>();
            }
            contact.PmStatus = "Open";
            contact.UnreadMessageCount = 0;
            Messenger.Default.Send(new Uri(@"//Views/PrivateMessagePage.xaml?userID=" + Uri.EscapeDataString(contact.UserName), UriKind.Relative));
        }
        public void AddMessage(ChatMessage msg, bool doScroll = true)
        {
            bool isLastInBatch = msg.QueuedMessageCount > 10 && (msg.QueuedMessageCount == msg.QueuedMessageNumber);
            AddMessage(msg.Sender, msg.Message, msg.MessageType, msg.MessageRelayTime, doScroll, isLastInBatch);
        }
        public void AddMessage(UserInfo user, string message, MessageType mt, DateTime timestamp, bool doScroll = true, bool isLastInBatch = false)
        {
            if (user == null)
                throw new InvalidOperationException("UserInfo is null");
            if (String.IsNullOrEmpty(message))
                return;
            if (user.Color == null)
                user.Color = "#000000";

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                lock (LockObject)
                {
                    MessageModel lastMsg = this.Messages.Count > 0 ? this.Messages.Last() : null;
                    bool showSender = !(user.UserName == "GreenText" || user.UserName == "RedText");
                    FontStyle style;
                    FontWeight weight;
                    StaticMethods.ParseFontStyle(user.FontStyle, out style, out weight);

                    if (lastMsg != null && timestamp.Subtract(LastMessageReceivedTime).TotalSeconds < 10 && lastMsg.UserID == user.UserID)
                    {
                        lastMsg.IsLastInBatch = isLastInBatch;
                        this.Messages.Remove(lastMsg);
                        lastMsg.MessageText += Environment.NewLine + message;
                        this.Messages.Add(lastMsg);

                    }
                    else
                    {
                        this.Messages.Add(new MessageModel(user.UserID, timestamp)
                        {
                            NickName = user.PrettyName,
                            IsUserNameVisible = showSender,
                            MessageText = message,
                            FontWeight = weight,
                            FontStyle = style,
                            FontColor = new SolidColorBrush(StaticMethods.ColorFromHex(user.Color)),
                            IsLastInBatch = isLastInBatch
                        });
                    }

                    LastMessageReceivedTime = timestamp;
                }
            });
        }
    }
}
